using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;

namespace ChessKit.Ui
{
  internal class DragAdorner : Adorner
  {
    private readonly UIElement _child;
    private readonly Size _originalSize;
    private Vector _offset;

    public DragAdorner(UIElement owner, UIElement adornElement, Size originalSize)
      : base(owner)
    {
      _child = adornElement;
      _originalSize = originalSize;
    }

    public Vector Offset
    {
      get { return _offset; }
      set
      {
        _offset = value;
        UpdatePosition();
      }
    }

    private void UpdatePosition()
    {
      var adornerLayer = (AdornerLayer)Parent;
      if (adornerLayer != null)
      {
        adornerLayer.Update(AdornedElement);
      }
    }

    protected override Visual GetVisualChild(int index)
    {
      return _child;
    }
    protected override int VisualChildrenCount
    {
      get { return 1; }
    }
    protected override Size MeasureOverride(Size finalSize)
    {
      _child.Measure(_originalSize);
      return _originalSize;
    }
    protected override Size ArrangeOverride(Size finalSize)
    {
      _child.Arrange(new Rect((Point)_offset, _originalSize));
      return _originalSize;
    }
  
    public void Dispose()
    {
      var adornerLayer = (AdornerLayer)Parent;
      if (adornerLayer != null)
      {
        adornerLayer.Remove(this);
      }
    }
  }
}